package com.yang.sso.oauth.model;

import cn.hutool.core.collection.CollectionUtil;
import com.yang.sso.oauth.enums.UserStatusEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;


import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: Islands
 * @create: 2024-04-11 20:51
 */

@Data
@NoArgsConstructor
public class MyUserDetails implements UserDetails {

    private Long userId;
    private String username;
    private String nickname;
    private String avatar;
    private String password;
    private Integer enabled;
    private List<String> roles;
    private Collection<SimpleGrantedAuthority>  authorities;


    public MyUserDetails(UserInfo info) {
        this.setUserId(info.getUserId());
        this.setUsername(info.getUsername());
        this.setAvatar(info.getAvatar());
        this.setNickname(info.getNickname());
        this.setPassword(info.getPassword());
        this.setEnabled(info.getEnabled().getValue());
        if (CollectionUtil.isNotEmpty(info.getPerms())) {
            authorities = info.getPerms().stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toSet());
        }
        this.setRoles(info.getRoles());

    }


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return authorities;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    /**
     * 过期
     * @return
     */
    @Override
    public boolean isAccountNonExpired() {
        return !this.enabled.equals(UserStatusEnum.OVERDUE.getValue());
    }

    /**
     * 锁定
     * @return
     */
    @Override
    public boolean isAccountNonLocked() {
        return !this.enabled.equals(UserStatusEnum.LOCK.getValue());
    }

    /**
     * 凭据未过期
     * @return
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return !this.enabled.equals(UserStatusEnum.OVERDUE.getValue());
    }

    @Override
    public boolean isEnabled() {
        return this.enabled.equals(UserStatusEnum.OFFLINE.getValue()) ||
                this.enabled.equals(UserStatusEnum.ONLINE.getValue());
    }
}
